<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form label-width="120px" inline>
      <el-form-item label="课程名称">
        <el-input v-model="course.courseName" style="width: 220px"/>
      </el-form-item>
      <el-form-item label="总课时数">
        <el-input v-model="course.lessonNum" style="width: 50px"/>
        课时
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input v-model="course.price" style="width: 100px"/>
        元
      </el-form-item>
    </el-form>
    <el-form label-width="120px" inline>
      <el-form-item label="授课教练">
        <el-select v-model="course.trainerName" clearable placeholder="请选择" @change="handleChangeTrainer">
          <el-option
            v-for="item in trainerList"
            :key="item.id"
            :label="item.trName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="擅长方向">
        <el-cascader
          clearable
          :show-all-levels="false"
          v-model="course.categoryId"
          :options="categoryList"
          :props="{ expandTrigger: 'hover'}"
          @change="handleChange"></el-cascader>
      </el-form-item>
    </el-form>
    <el-form label-width="120px">
      <el-form-item label="课程简述">
        <el-input type="textarea" v-model="course.descrip" :rows="6" style="width: 60%"></el-input>
      </el-form-item>
      <!-- 课程封面 -->
      <el-form-item label="课程封面">
        <el-upload
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error="handleAvatarError"
          :action="BASE_API+'/file/uploadInAdmin'"
          :data="UPLOADFILEBIZ"
          :headers="headers"
          name="avatar"
          class="avatar-uploader"
        >
          <img v-if="course.cover" :src="course.cover">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">保 存</el-button>
        <el-button v-show="canPublish" type="success" @click="handlePublish">发 布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import courseAPI from '@/api/course'
import {getToken} from '@/utils/auth'
import categoryAPI from "@/api/category"; // get token from cookie
import trainerAPI from "@/api/trainer";

export default {
  data() {
    return {
      cascaderList: [],
      categoryList: [],
      regionList: [],
      trainerList: [],
      PUBLISHED: 1,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      headers: {
        'token': getToken()
      },
      UPLOADFILEBIZ: {biz: 'course_cover'},
      canPublish: false, // 是否可用发布按钮
      BASE_API: 'http://localhost:8099',
      // 初始化员工默认数据
      course: {},
      saveBtnDisabled: false // 保存按钮是否禁用，防止表单重复提交
    }
  },
  // 页面渲染成功
  created() {
    categoryAPI.getCategoryCascader().then(res => {
      this.categoryList = res.data
    })
    trainerAPI.getAllTrainer().then(res => {
      this.trainerList = res.data
    })
    if (this.$route.params.id) {
      this.fetchDataById(this.$route.params.id)
    }
  },
  methods: {
    handleChange(val) {
      console.log(val)
      if (Array.isArray(val)) {
        for (let i = 0; i < val.length; i++) {
          this.course.categoryId = val[1]
        }
      }
      // this.trainer.expertise = val.slice(-1).toString()
      // this.cascaderList.push(this.searchObj.expertise)
      console.log(this.course.categoryId)
    },
    handleChangeTrainer(val) {
      this.course.trainerId = val
      // console.log(this.course)
      // console.log(val);
    },
    handleRemove(file) {
      console.log(file)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.course.picture
      this.dialogVisible = true
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      if (res.code === 20000) {
        // console.log(res)
        this.course.cover = res.data
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error('上传失败 （非0）')
      }
    },
    // 错误处理
    handleAvatarError() {
      console.log('error')
      this.$message.error('上传失败（http失败）')
    },
    // 上传校验
    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    saveOrUpdate() {
      // 禁用保存按钮
      this.saveBtnDisabled = true
      if (!this.course.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },
    fetchDataById(id) {
      courseAPI.getCourseById(id).then(res => {
        this.course = res.data
        this.canPublish = this.course.status === 0
        // for (let i = 0; i < this.course.partList.length; i++) {
        //   let child = []
        //   child.push(this.course.partList[i].parentId)
        //   child.push(this.course.partList[i].id)
        //   this.cascaderList.push(child)
        // }
        // this.handleChange(this.cascaderList)
      })
    },
    saveData() {
      courseAPI.saveCourse(this.course).then(response => {
        this.$message({
          type: 'success',
          message: '新增成功！'
        })
        this.$router.push({path: '/course/list'})
      })
    },
    // 根据id更新记录
    updateData() {
      courseAPI.updateById(this.course.id, this.course).then(response => {
        this.$message({
          type: 'success',
          message: '修改成功！'
        })
        this.$router.push({path: '/course/list'})
      })
    },
    handlePublish() {
      this.$confirm('是否已经确认信息无误,准备发布课程？', '发布课程', {
        distinguishCancelAndClose: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定发布'
      }).then(() => {
        courseAPI.changeStatusById(this.course.id, this.PUBLISHED).then(res => {
          // this.course.status = this.PUBLISHED
          this.fetchDataById(this.course.id)
          this.$message.success('发布成功！')
        })
      }).catch(action => {
        this.$message({
          type: 'info',
          message: '取消发布'
        })
      })
    }
  }
}
</script>

<style scoped>
.avatar-uploader .avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409EFF;
}

.avatar-uploader img {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
